<!-- 待完成 -->
<template>
  <div class="a-todo">
    <div class="list">
      <div style="width: 100%;height: 100%;">
        <div style="width: 100%;display: flex;flex-direction: column;height: 100%;overflow: hidden;">
          <div class="title" style="position: relative;">
            <span class="fa fa-plus" title="新建任务" @click="add()"></span>
            代办事项
            <span style="cursor: pointer;position: absolute;top:8px;right:34px" class="fa" :class="{
              'fa-credit-card': !showList,
              'fa-align-justify': showList
            }" title="切换样式" @click="changeListItemType()"></span>
            <span style="cursor: pointer;position: absolute;top:8px;right:8px" class="fa"
              :class="{ 'fa-compress': !showADate, 'fa-expand': showADate }" title="伸展" @click="expand()"></span>
          </div>
          <div style="height: 1px;width: calc(100% - 20px);margin: 8px auto;background: var(--bs-light-border-subtle);">
          </div>
          <div v-if="totalTime > 0" class="alert alert-primary" role="alert"
            style="padding: 4px 10px;font-size: 0.8rem;margin-bottom: 0;font-weight: bold;">
            总工时：{{ totalTime ? totalTime.toFixed(1) : 0 }}d
          </div>

          <div class="list">
            <div v-if="list.length === 0" class="no-todo">
              暂无任务
              <button type="button" class="btn btn-primary btn-sm" @click.stop="add()">
                新建一个
              </button>
              吧
            </div>
            <div v-if="showList">
              <div v-for="(list, listIndex) in showTodoList" style="margin-bottom:20px">
                <div class="d-title">
                  <span
                    style="display: inline-block;height: 0.6rem;width: 4px;background:var(--bs-primary);border-radius: 4px;"></span>
                  {{ list.type ? list.type : "其他" }}
                  <span class="badge text-bg-primary" v-if="list.time">{{ list.time }}d</span>
                </div>

                <div class="item" :class="{ 'on-edit': editIndex === item.index }" v-for="(item, index) in list.value"
                  @contextmenu.prevent="showRightMenu($event, item.index)">
                  <span class="item-title" :title="item.title" @click="edit(item.index)" :style="{
              'font-size': item.title.length > 8 ? '0.8rem' : '1rem'
            }">{{ item.title }}</span>
                  <span v-if="item.status !== '已完成'" class="fa fa-check opreation" title="完成任务"
                    @click="finishWork(item.index, true)"></span>
                  <span v-if="item.status === '已完成'" class="fa fa-repeat opreation" title="重置任务"
                    @click="finishWork(item.index, false)"></span>
                  <span class="fa fa-trash opreation" title="删除任务" @click="remove(item.index)"></span>
                </div>
              </div>
            </div>

            <div v-if="!showList">
              <div v-for="(list, listIndex) in showTodoList" style="margin-bottom:20px">
                <div class="d-title">
                  <span
                    style="display: inline-block;height: 0.6rem;width: 4px;background:var(--bs-primary);border-radius: 4px;"></span>
                  {{ list.type ? list.type : "其他" }}
                  <span class="badge text-bg-primary" v-if="list.time">{{ list.time ? list.time.toFixed(1) : 0
                    }}d</span>
                </div>

                <div class="item max" :class="{ 'on-edit': editIndex === item.index }"
                  v-for="(item, index) in list.value" @contextmenu.prevent="showRightMenu($event, item.index)">
                  <div style="flex:1" @click="edit(item.index)">
                    <div class="item-title" :style="{
              'font-size': item.title.length > 8 ? '0.8rem' : '1rem'
            }">
                      {{ item.title }}
                      <span class="badge text-bg-light"
                        style="display: inline-block;line-height: 0.6rem;background-color: #fff!important;"
                        v-if="item.time">{{ item.time ? item.time.toFixed(1) : "" }}d</span>
                    </div>
                    <div class="item-detail">{{ item.detail }}</div>
                  </div>
                  <div class="opreation-max">
                    <span v-if="item.status !== '已完成'" class="fa fa-check" title="完成任务"
                      @click="finishWork(item.index, true)"></span>
                    <span v-if="item.status === '已完成'" class="fa fa-repeat" title="重置任务"
                      @click="finishWork(item.index, false)"></span>
                    <span class="fa fa-trash" title="删除任务" @click="remove(item.index)"></span>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="vpopmenu" v-if="rightMenuStyle.show" :style="{
              left: rightMenuStyle.left + 'px',
              top: rightMenuStyle.top + 'px'
            }">
            <!-- <div @click.stop="top(editIndex);">
              <i class="fa fa-arrow-up"></i>
              置顶
            </div> -->
            <!-- <div @click.stop="finish(editIndex);" >
              <i class="fa fa-check"></i>
              完成
            </div> -->
            <div @click="nextNowDate(editIndex)" title="调整到今日" v-if="list[editIndex].year !== nowDate.getFullYear() ||
              list[editIndex].moth !== nowDate.getMonth() ||
              list[editIndex].date !== nowDate.getDate()
              ">
              <i class="fa-solid fa-calendar-day"></i>
              转到今日
            </div>
            <div @click="nextTodo(editIndex)" title="添加到明天任务清单">
              <i class="fa-regular fa-calendar-plus"></i>
              预排到明天
            </div>
            <div @click="toNextDay(editIndex)" title="顺延至下一天">
              <i class="fa-solid fa-calendar-week"></i>
              延期一天
            </div>
            <!-- <div class="delete" @click.stop="remove(editIndex);">
              <i class="fa fa-trash"></i>
              删除
            </div> -->
          </div>
        </div>
      </div>
    </div>

    <div id="addModal" class="modal" :class="showAdd ? 'modal-show' : ''">
      <div class="modal-dialog-centered" style="height: 100%;">
        <div class="modal-content">
          <div style="display: flex;margin-bottom: 10px;">
            <h3 style="flex: 1;" class="m-title">
              {{ managerType ? "选择/管理项目" : "添加计划" }}
            </h3>
            <button type="button" class="btn-close" aria-label="Close" @click="closeAdd()"></button>
          </div>
          <div style="flex: 1;height: 0;overflow-y: auto;">

            <div v-if="managerType">
              <div style="margin-bottom: 10px;">
                <button type="button" class="btn btn-light" @click="managerType = false">
                  <i class="fa-solid fa-arrow-left-long "></i>
                </button>
                <button type="button" class="btn btn-primary" @click="addWorkType()">
                  新增一个项目
                </button>
              </div>
              <div class="list-group" style="max-height: 400px;overflow: auto;">
                <button type="button" class="list-group-item list-group-item-action" v-for="(type, index) in typeList"
                  @click="selectWorkType(type)">
                  <div style="display: flex;">
                    <div style="flex: 1;line-height: 31px;">{{ type.name }}</div>
                    <div class="btn-group" role="group">
                      <button type="button" class="btn btn-light btn-sm" @click.stop="changeTypeSort(index, true)">
                        <i class="fa-solid fa-arrow-up"></i>
                      </button>
                      <button type="button" class="btn btn-light btn-sm" @click.stop="changeTypeSort(index, false)">
                        <i class="fa-solid fa-arrow-down"></i>
                      </button>
                      <button type="button" class="btn btn-danger btn-sm" @click.stop="removeWorkType(type)">
                        <i class="fa-solid fa-trash-can "></i>
                      </button>
                    </div>
                  </div>
                </button>
              </div>
            </div>
            <div v-if="!managerType">
              <form class="row g-3 needs-validation" novalidate style="margin: 0;">
                <div style="display: flex;">
                  <div style="margin-right: 20px;">
                    <div class="btn-group-vertical" role="group" aria-label="Vertical radio toggle button group">
                      <input type="radio" class="btn-check" name="jsyj" id="jsyj" autocomplete="off"
                        :checked="addWorkForm.scope === '技术研发'"
                        @click="addWorkForm.scope = (addWorkForm.scope === '技术研发' ? '' : '技术研发')" />
                      <label class="btn btn-outline-secondary" for="jsyj">技术研发</label>
                      <input type="radio" class="btn-check" name="zxxq" id="zxxq" autocomplete="off"
                        :checked="addWorkForm.scope === '主线需求'"
                        @click="addWorkForm.scope = (addWorkForm.scope === '主线需求' ? '' : '主线需求')" />
                      <label class="btn btn-outline-secondary" for="zxxq">主线需求</label>
                      <input type="radio" class="btn-check" name="dwzc" id="dwzc" autocomplete="off"
                        :checked="addWorkForm.scope === '对外支持'"
                        @click="addWorkForm.scope = (addWorkForm.scope === '对外支持' ? '' : '对外支持')" />
                      <label class="btn btn-outline-secondary" for="dwzc">对外支持</label>
                      <input type="radio" class="btn-check" name="debug" id="debug" autocomplete="off"
                        :checked="addWorkForm.scope === 'Debug'"
                        @click="addWorkForm.scope = (addWorkForm.scope === 'Debug' ? '' : 'Debug')" />
                      <label class="btn btn-outline-secondary" for="debug">Debug</label>
                      <input type="radio" class="btn-check" name="dzkf" id="dzkf" autocomplete="off"
                        :checked="addWorkForm.scope === '定制开发'"
                        @click="addWorkForm.scope = (addWorkForm.scope === '定制开发' ? '' : '定制开发')" />
                      <label class="btn btn-outline-secondary" for="dzkf">定制开发</label>
                      <input type="radio" class="btn-check" name="dsfdj" id="dsfdj" autocomplete="off"
                        :checked="addWorkForm.scope === '第三方对接'"
                        @click="addWorkForm.scope = (addWorkForm.scope === '第三方对接' ? '' : '第三方对接')" />
                      <label class="btn btn-outline-secondary" for="dsfdj">第三方对接</label>
                      <input type="radio" class="btn-check" name="qt" id="qt" autocomplete="off"
                        :checked="addWorkForm.scope === '其他'"
                        @click="addWorkForm.scope = (addWorkForm.scope === '其他' ? '' : '其他')" />
                      <label class="btn btn-outline-secondary" for="qt">其他</label>
                    </div>
                  </div>
                  <div style="flex: 1;border-left: 1px var(--bs-border-color) solid;padding-left: 20px;">
                    <div class="mb-3">
                      <label for="plane-input-title" class="form-label">标题：</label>
                      <input v-model="addWorkForm.title" class="form-control" id="plane-input-title"
                        placeholder="请输入标题" />
                    </div>
                    <label for="plane-input-time" class="form-label">项目：
                      <span style="font-size: 0.8rem;color: #999;">{{ addWorkForm.scope === '定制开发' || addWorkForm.scope
              === '第三方对接' || addWorkForm.scope === '对外支持' ? `一般${addWorkForm.scope}不用填项目` : '' }}</span>

                    </label>
                    <div class="input-group mb-3">
                      <input type="text" class="form-control" placeholder="请选择项目" v-model="addWorkForm.type"
                        aria-label="请选择项目" aria-describedby="clear-type" @focus="managerType = true">
                      <button class="btn btn-outline-secondary" type="button" id="clear-type"
                        @click="addWorkForm.type = ''">
                        <i class="fa-solid fa-trash-can "></i></button>
                    </div>
                    <div class="mb-3">
                      <label for="plane-input-title" class="form-label">日期：</label>
                      <input style="cursor: pointer" v-model="addWorkForm.date" class="form-control"
                        id="plane-input-date" placeholder="请选择日期" @click="showChoiceDateFun" />

                      <div @click="e => e.stopPropagation()" v-if="showChoiceDate"
                        style="position: absolute;z-index: 99;box-shadow: 0 4px 20px rgba(0,0,0,0.2);"
                        class="data-picker">
                        <a-date :value="choiceDate" :select="true" @selected="selectDate"></a-date>
                      </div>
                    </div>
                    <label for="plane-input-time" class="form-label">时长：</label>
                    <div class="input-group  mb-3">
                      <input type="email" class="form-control" id="plane-input-time" placeholder="请输入时长（天）"
                        v-model="addWorkForm.time" aria-describedby="plane-input-time-affter" />
                      <span class="input-group-text" id="plane-input-time-affter">天 约{{ (addWorkForm.time *
              7.5).toFixed(1)
                        }}小时</span>
                    </div>
                    <input type="range" class="form-range" min="0" max="1" step="0.1" id="customRange3"
                      v-model="addWorkForm.time" />
                    <div class="mb-3">
                      <label for="plane-input-status" class="form-label">状态：</label>
                      <div class="btn-group" role="group" aria-label="Basic radio toggle button group">
                        <input type="radio" class="btn-check" name="btnradio" id="btnradio1" autocomplete="off"
                          :checked="addWorkForm.status === '进行中'">
                        <label class="btn btn-outline-primary btn-sm" for="btnradio1"
                          @click="addWorkForm.status = '进行中'">进行中</label>

                        <input type="radio" class="btn-check" name="btnradio" id="btnradio2" autocomplete="off"
                          :checked="addWorkForm.status === '已完成'">
                        <label class="btn btn-outline-primary btn-sm" for="btnradio2"
                          @click="addWorkForm.status = '已完成'">已完成</label>
                      </div>
                    </div>
                    <div class="mb-3">
                      <label for="plane-input-remark" class="form-label">备注：</label>
                      <textarea class="form-control" id="plane-input-remark" rows="3" v-model="addWorkForm.detail"
                        style="max-height:200px;transition: none;" placeholder="请输入备注"></textarea>
                    </div>
                  </div>
                </div>
                <button type="button" class="btn btn-primary" @click="addWork()">
                  确认
                </button>
              </form>
            </div>

          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 加载模块
import ADate from "./ADate.vue";

let ipcRenderer;
if (window.require) {
  ipcRenderer = window.require("electron").ipcRenderer;
}
const nedb = require("nedb");
const aplaneTypeDb = new nedb({
  filename: "/data/aplane-type.db",
  autoload: true
});
import { globalBus } from "@/assets/js/globalBus.js";
import Swal from "sweetalert2";

export default {
  name: "ATodo",
  components: { ADate },
  data() {
    return {
      showList: false,
      showChoiceDate: false,
      showADate: true,
      //任务数据库
      aplaneTodoDb: undefined,
      typeList: [],
      list: [],
      showTodoList: [],
      editIndex: -1,
      choiceDate: {
        date: "",
        moth: "",
        year: ""
      },
      rightMenuStyle: {
        top: 0,
        left: 0,
        show: false
      },
      showAddText: false,
      showAdd: false,
      showAddType: false,
      managerType: false,
      addWorkForm: {
        index: "",
        _id: "",
        title: "",
        scope: "",
        detail: "",
        status: "进行中",
        type: "",
        time: 0,
        planeText: ""
      },
      showTypeSelect: false,
      //当前加载的数据库
      loadDate: {
        year: "",
        moth: "",
        date: "",
        week: ""
      },
      nowDate: new Date(),
      totalTime: 0
    };
  },
  created() {
    let _this = this;
    let date = new Date();
    this.choiceDate = {
      date: date.getDate(),
      month: date.getMonth(),
      year: date.getFullYear()
    };
    this.addWorkForm.date =
      date.getFullYear() +
      "年" +
      (date.getMonth() + 1) +
      "月" +
      date.getDate() +
      "日";
    //获取日期后回调这里
    globalBus.$on("add_palne", this.add)
    globalBus.$on("edit_plane_by_form", this.editByForm)
    globalBus.$on("aDate_changeDateBack", this.changeDateBack);
    globalBus.$on("aPlane_reload", this.reloadPlane);
  },
  methods: {
    reloadPlane() {
      this.aplaneTodoDb = new nedb({
        filename:
          "/data/aplane-todo_" +
          this.loadDate.year +
          "-" +
          this.loadDate.moth +
          ".db",
        autoload: true
      });
    },
    changeDateBack(date) {
      this.choiceDate = {
        date: date.date,
        month: date.moth,
        year: date.year
      };
      this.addWorkForm.date =
        date.year + "年" + (date.moth + 1) + "月" + date.date + "日";
      this.loadTodo(date);
    },
    showChoiceDateFun(e) {
      e.stopPropagation();
      this.showChoiceDate = true;
    },
    selectDate(date) {
      this.showChoiceDate = false;
      this.choiceDate = date;
      this.addWorkForm.date =
        date.year + "年" + (date.month + 1) + "月" + date.date + "日";
    },
    changeListItemType() {
      this.showList = !this.showList;
    },
    sortTypes() {
      let s = this.typeList.sort((a, b) => a.sort - b.sort);
      for (let index = 0; index < this.typeList.length; index++) {
        this.typeList[index].sort = index;
        aplaneTypeDb.update(
          {
            _id: this.typeList[index]._id
          },
          this.typeList[index],
          {},
          (err, ret) => { }
        );
      }
    },
    //展开任务
    expand() {
      this.showADate = !this.showADate;
      globalBus.$emit("plane_todo_expand", this.showADate);
    },
    //完成任务
    finishWork(index, finish) {
      let _this = this;
      let data = this.list[index];
      if (finish) {
        data.status = "已完成";
      } else {
        data.status = "进行中";
      }
      let finishTag = 0;
      let finishFun = function () {
        finishTag++;
        if (finishTag === 2) {
          //_this.list.splice(index, 1, data)
          _this.refreshMini(data);
          globalBus.$emit("aPlane_reload", date => { });
        }
      };
      _this.updateBeforeAndNext(data, "before", finishFun);
      let nextDate = new Date(data.year, data.moth, data.date);
      nextDate = new Date(nextDate.setDate(nextDate.getDate() + 1));
      _this.updateBeforeAndNext(
        {
          year: nextDate.getFullYear(),
          moth: nextDate.getMonth(),
          date: nextDate.getDate(),
          title: data.title,
          status: data.status
        },
        "after",
        finishFun
      );
    },
    //如果这是一个延期工作 更新时候全部更新
    updateBeforeAndNext(data, to, callBack) {
      const _this = this;
      let db;
      if (
        _this.loadDate.year !== data.year ||
        _this.loadDate.moth !== data.moth
      ) {
        db = new nedb({
          filename: "/data/aplane-todo_" + data.year + "-" + data.moth + ".db",
          autoload: true
        });
      } else {
        db = _this.aplaneTodoDb;
      }
      db.find(
        {
          year: data.year,
          moth: data.moth,
          date: data.date,
          title: data.title
        },
        (err, docs) => {
          if (docs.length > 0) {
            docs[0].status = data.status;
            _this.aplaneTodoDb.update(
              {
                _id: docs[0]._id
              },
              docs[0],
              {},
              (err, ret) => {
                let nextDate = new Date(data.year, data.moth, data.date);
                if (to === "before") {
                  nextDate = new Date(nextDate.setDate(nextDate.getDate() - 1));
                } else if (to === "after") {
                  nextDate = new Date(nextDate.setDate(nextDate.getDate() + 1));
                }
                _this.updateBeforeAndNext(
                  {
                    year: nextDate.getFullYear(),
                    moth: nextDate.getMonth(),
                    date: nextDate.getDate(),
                    title: data.title,
                    status: data.status
                  },
                  to,
                  callBack
                );
              }
            );
          } else {
            callBack();
          }
        }
      );
    },
    //整理list
    filterList() {
      this.showTodoList.splice(0, this.showTodoList.length);
      this.totalTime = 0;
      let map = new Map();
      let timeMap = new Map();
      for (let x in this.list) {
        let item = this.list[x];
        item.index = x;
        let arr = map.get(item.type);
        let time = timeMap.get(item.type);
        item.time = item.time ? item.time : 0;
        if (arr) {
          arr.push(item);
        } else {
          map.set(item.type, [item]);
        }
        timeMap.set(item.type, (time ? time : 0) + parseFloat(item.time));
        this.totalTime += parseFloat(item.time);
      }
      map.forEach((value, key) => {
        this.showTodoList.push({
          type: key,
          value: value,
          time: timeMap.get(key)
        });
      });
    },
    addWorkText() {
      if (!this.addWorkForm.planeText) {
        Swal.fire({
          title: `请输入内容`,
          icon: "error"
        });
      }
      let text = this.addWorkForm.planeText.trim();
      let texts = text.split("\n\n");
      let type = "";
      let _this = this;
      for (let x in texts) {
        let planeInfo = texts[x].split("\n");
        let titleIndex = 0;
        let title, deatil;
        let okNum = 0;
        if (
          ((planeInfo[0].charAt(0) === "【" ||
            planeInfo[0].charAt(0) === "[") &&
            planeInfo[0].charAt(planeInfo[0].length - 1) === "】") ||
          planeInfo[0].charAt(planeInfo[0].length - 1) === "]"
        ) {
          type = planeInfo[0].substring(1, planeInfo[0].length - 1);
          titleIndex = 1;
        }
        title = planeInfo[titleIndex];
        deatil = planeInfo[titleIndex + 1];
        let reg = /^(\d{1,2})+[.,、。， ]+/g;
        title = title.replace(reg, "").trim();
        if (type) {
          aplaneTypeDb.find(
            {
              name: type
            },
            function (err, docs) {
              if (docs.length === 0) {
                aplaneTypeDb.insert(
                  {
                    name: type
                  },
                  (err, ret) => { }
                );
              }
            }
          );
        }
        (function (x) {
          _this.insertWork(
            {
              title: title,
              detail: deatil,
              status: "进行中",
              type: type,
              year: _this.loadDate.year,
              moth: _this.loadDate.moth,
              date: _this.loadDate.date
            },
            (err, ret) => {
              if (err) {
                okNum++;
                _this.list.push(ret);
                _this.filterList();
              }
              if (x === texts.length - 1) {
                Swal.fire({
                  title:
                    `成功添加` +
                    okNum +
                    `个任务` +
                    (okNum === texts.length
                      ? ""
                      : ",失败" + (texts.length - okNum) + "个"),
                  icon: okNum === texts.length ? "success" : "error"
                });
                _this.closeAdd();
              }
            }
          );
        })(x);
      }
    },
    addNextTodoAfter(data, date, type) {
      const _this = this;
      if (type === "预排") {
        data.year = date.getFullYear();
        data.moth = date.getMonth();
        data.date = date.getDate();
        data.status = "进行中";
        let id = data._id + "";
        this.insertWork(data, (success, ret) => {
          if (success) {
            this.aplaneTodoDb.remove(
              {
                _id: id
              },
              {},
              function (err, numRemoved) {
                _this.refreshMini(data);
              }
            );
          } else {
            Swal.fire({
              title: `任务已存在`,
              icon: "error"
            });
          }
        });
      } else if (type === "延期") {
        data.year = date.getFullYear();
        data.moth = date.getMonth();
        data.date = date.getDate();
        data.tag = "延期";
        data.status = "进行中";
        this.insertWork(data, (success, ret) => {
          if (success) {
            _this.refreshMini(data);
          } else {
            Swal.fire({
              title: `任务已存在`,
              icon: "error"
            });
          }
        });
      }
    },
    addNextTodo(nextDate, data, type) {
      const _this = this;
      const week = nextDate.getDay();
      if (week === 0 || week === 6) {
        Swal.fire({
          title: "明天是周末哦，继续添加吗?",
          showDenyButton: true,
          showCancelButton: true,
          showConfirmButton: true,
          denyButtonText: `添加`,
          confirmButtonText: `顺延下个工作日`,
          cancelButtonText: `取消`
        }).then(result => {
          let insert = false;
          if (result.isConfirmed) {
            if (week === 6) {
              nextDate = new Date(nextDate.setDate(nextDate.getDate() + 2));
            } else if (week === 0) {
              nextDate = new Date(nextDate.setDate(nextDate.getDate() + 1));
            }
            insert = true;
          } else if (result.isDenied) {
            insert = true;
          }
          if (!insert) {
            return;
          }
          _this.addNextTodoAfter(data, nextDate, type);
        });
      } else {
        _this.addNextTodoAfter(data, nextDate, type);
      }
    },
    //调整到今天
    nextNowDate(index) {
      const date = new Date();
      let id = this.list[index]._id + ''
      delete this.list[index]._id;
      this.list[index].year = date.getFullYear();
      this.list[index].moth = date.getMonth();
      this.list[index].date = date.getDate();
      this.list[index].status = "进行中";
      this.insertWork(this.list[index], (success, ret) => {
        if (success) {
          this.aplaneTodoDb.remove(
            {
              _id: id
            },
            {},
            function (err, numRemoved) {
            }
          );
        } else {
          Swal.fire({
            title: `任务已存在`,
            icon: "error"
          });
        }
      });
    },
    //预排 安排到明天
    nextTodo(index) {
      const curTime = new Date();
      const nextDate = new Date(curTime.setDate(curTime.getDate() + 1));
      this.addNextTodo(nextDate, this.list[index], "预排");
    },
    //延期
    toNextDay(index) {
      const curTime = new Date(
        this.loadDate.year,
        this.loadDate.moth,
        this.loadDate.date
      );
      const nextDate = new Date(curTime.setDate(curTime.getDate() + 1));
      this.addNextTodo(nextDate, this.list[index], "延期");
    },
    remove(index) {
      const _this = this;
      Swal.fire({
        title: '确认删除"' + this.list[index].title + '"吗?',
        showDenyButton: true,
        showCancelButton: true,
        showConfirmButton: false,
        denyButtonText: `确认`,
        cancelButtonText: `取消`
      }).then(result => {
        if (result.isDenied) {
          // 删除
          _this.aplaneTodoDb.remove(
            {
              _id: this.list[index]._id
            },
            {},
            function (err, numRemoved) {
              _this.refreshMini(_this.list[index]);
              _this.list.splice(index, 1);
              globalBus.$emit("aPlane_reload", date => { });
            }
          );
        }
      });
    },
    addText() {
      this.showAddText = true;
    },
    add() {
      this.showAdd = true;
    },
    selectWorkType(type) {
      this.managerType = false;
      this.addWorkForm.type = type.name;
    },
    showTypeSelectFun() {
      this.showTypeSelect = !this.showTypeSelect;
    },
    removeWorkType(type) {
      let _this = this;
      Swal.fire({
        title: '确认删除"' + type.name + '"吗?',
        showDenyButton: true,
        showCancelButton: true,
        showConfirmButton: false,
        denyButtonText: `确认`,
        cancelButtonText: `取消`
      }).then(result => {
        if (result.isDenied) {
          aplaneTypeDb.remove(
            {
              _id: type._id
            },
            {},
            function (err, numRemoved) {
              _this.loadTypes();
              globalBus.$emit("aPlane_reload", date => { });
            }
          );
          if (type.name === _this.addWorkForm.type) {
            _this.addWorkForm.type = "";
          }
        }
      });
    },
    changeTypeSort(index, up) {
      let type = this.typeList[index];
      if (!type.sort) {
        type.sort = 0;
      }
      if (up && index > 0) {
        if (!this.typeList[index - 1].sort) {
          this.typeList[index - 1].sort = 0;
        }
        type.sort = this.typeList[index - 1].sort - 1;
        this.sortTypes();
      } else if (index < this.typeList.length) {
        if (!this.typeList[index + 1].sort) {
          this.typeList[index + 1].sort = 0;
        }
        type.sort = this.typeList[index + 1].sort + 1;
        this.sortTypes();
      }
    },
    saveWorkType(name) {
      let _this = this;
      aplaneTypeDb.find(
        {
          name: name
        },
        function (err, docs) {
          if (docs.length === 0) {
            // 插入单项
            aplaneTypeDb.insert(
              {
                name: name,
                sort: 0
              },
              (err, ret) => {
                if (ret) {
                  Swal.fire({
                    title: `已添加`,
                    icon: "success"
                  });
                  globalBus.$emit("aPlane_reload", date => { });
                  _this.loadTypes();
                } else {
                  Swal.fire({
                    title: `添加失败`,
                    icon: "error"
                  });
                }
              }
            );
          } else {
            Swal.fire({
              title: `该类型已存在`,
              icon: "error"
            });
          }
        }
      );
    },
    addWorkType() {
      Swal.fire({
        input: "text",
        inputPlaceholder: "请输入类型",
        inputAttributes: {
          autocapitalize: "off"
        },
        showCancelButton: false,
        confirmButtonText: "添加",
        showLoaderOnConfirm: true,
        background: this.$store.state.theme.themeType == 'dark' ? '#000' : '#fff'
      }).then(result => {
        if (result.isConfirmed && result.value) {
          this.saveWorkType(result.value);
        }
      });
    },
    addWork() {
      let _this = this;
      if (!this.addWorkForm.scope) {
        Swal.fire({
          title: `类型不能为空！请在右侧选择类型：主线需求/技术研发...等`,
          icon: "error"
        });
      } else if ((this.addWorkForm.scope === "主线需求" ) && !this.addWorkForm.type) {
        Swal.fire({
          title: `${this.addWorkForm.scope}所属项目不能为空！`,
          icon: "error"
        });
      } else if (!this.addWorkForm.title) {
        Swal.fire({
          title: `标题不能为空！`,
          icon: "error"
        });
      } else {
        this.addWorkForm.title = this.addWorkForm.title.trim();
        this.addWorkForm.detail = this.addWorkForm.detail
          ? this.addWorkForm.detail.trim()
          : "";

        if (this.addWorkForm._id) {
          let db = this.aplaneTodoDb
          if (
            _this.loadDate.year + "-" + _this.loadDate.moth !==
            this.choiceDate.year + "-" + this.choiceDate.month
          ) {
            db = new nedb({
              filename: "/data/aplane-todo_" + this.choiceDate.year + "-" + this.choiceDate.month + ".db",
              autoload: true
            });
          }
          db.remove(
            {
              _id: this.addWorkForm._id
            },
            {},
            function (err, numRemoved) {
              _this.insertWork(
                {
                  title: _this.addWorkForm.title,
                  detail: _this.addWorkForm.detail,
                  status: _this.addWorkForm.status ? _this.addWorkForm.status : "进行中",
                  scope: _this.addWorkForm.scope,
                  time: parseFloat(_this.addWorkForm.time),
                  type: _this.addWorkForm.type,
                  year: _this.choiceDate.year,
                  moth: _this.choiceDate.month,
                  date: _this.choiceDate.date
                },
                (err, ret) => {
                  if (err) {
                    _this.list.push(ret);
                    _this.closeAdd();
                  } else {
                    Swal.fire({
                      title: `任务已存在`,
                      icon: "error"
                    });
                  }
                }
              );
            }
          );
        } else {
          _this.insertWork(
            {
              title: _this.addWorkForm.title,
              detail: _this.addWorkForm.detail,
              status: _this.addWorkForm.status ? _this.addWorkForm.status : "进行中",
              scope: _this.addWorkForm.scope,
              time: parseFloat(_this.addWorkForm.time),
              type: _this.addWorkForm.type,
              year: _this.choiceDate.year,
              moth: _this.choiceDate.month,
              date: _this.choiceDate.date
            },
            (err, ret) => {
              if (err) {
                _this.list.push(ret);
                _this.closeAdd();
              } else {
                Swal.fire({
                  title: `任务已存在`,
                  icon: "error"
                });
              }
            }
          );
        }


      }
    },
    refreshMini(date) {
      if (!ipcRenderer) {
        return;
      }
      let curTime = new Date();
      if (
        curTime.getFullYear() === date.year &&
        curTime.getMonth() === date.moth &&
        curTime.getDate() === date.date
      ) {
        ipcRenderer.send("mini-plane-refresh");
      }
    },
    insertWork(data, callBack) {
      let _this = this;
      let insertDb = _this.aplaneTodoDb;
      if (
        _this.loadDate.year + "-" + _this.loadDate.moth !==
        data.year + "-" + data.moth
      ) {
        insertDb = new nedb({
          filename: "/data/aplane-todo_" + data.year + "-" + data.moth + ".db",
          autoload: true
        });
      }
      delete data._id;
      insertDb.find(
        {
          year: data.year,
          moth: data.moth,
          date: data.date,
          title: data.title
        },
        function (err, docs) {
          if (docs.length === 0) {
            insertDb.insert(
              {
                year: data.year,
                moth: data.moth,
                date: data.date,
                title: data.title,
                detail: data.detail,
                status: data.status ? data.status : '进行中',
                type: data.type,
                scope: data.scope,
                time: data.time
              },
              (err, docs) => {
                globalBus.$emit("aPlane_reload", data);
                _this.refreshMini(data);
                callBack(true, docs);
              }
            );
          } else {
            callBack(false, docs);
          }
        }
      );
    },
    closeAdd() {
      this.showAddText = false;
      this.showAdd = false;
      this.addWorkForm._id = "";
      this.addWorkForm.status = "进行中";
      this.addWorkForm.title = "";
      this.addWorkForm.detail = "";
      this.addWorkForm.type = "";
      this.addWorkForm.scope = "";
      this.addWorkForm.time = 0;
      this.addWorkForm.time = 0;
    },
    edit(index) {
      this.managerType = false;
      this.choiceDate = {
        year: this.list[index].year,
        month: this.list[index].moth,
        date: this.list[index].date
      };

      this.addWorkForm = {
        ...this.list[index],
        date:
          this.choiceDate.year +
          "年" +
          (this.choiceDate.month + 1) +
          "月" +
          this.choiceDate.date +
          "日"
      };
      this.showAdd = true;
    },
    editByForm(form) {
      this.managerType = false;
      this.choiceDate = {
        year: form.year,
        month: form.moth,
        date: form.date
      };

      this.addWorkForm = {
        ...form,
        date:
          this.choiceDate.year +
          "年" +
          (this.choiceDate.month + 1) +
          "月" +
          this.choiceDate.date +
          "日"
      };
      this.showAdd = true;
    },
    showRightMenu(e, index) {
      this.editIndex = index;
      this.rightMenuStyle.left = e.x;
      this.rightMenuStyle.top = e.y;
      if (e.y + 130 > e.view.innerHeight) {
        this.rightMenuStyle.top = e.view.innerHeight - 130;
      }
      this.rightMenuStyle.show = true;
    },
    clickOther(e) {
      if (e.srcElement.className.indexOf("swal2") !== -1) {
        return;
      }
      this.showChoiceDate = false;
      this.showAddType = false;
      this.rightMenuStyle.show = false;
      this.editIndex = -1;
      this.showTypeSelect = false;
    },
    loadTypes() {
      let _this = this;
      // 查询所有结果集
      aplaneTypeDb.find({}, function (err, docs) {
        _this.typeList = docs;
        _this.sortTypes();
        if (docs.length === 0) {
          _this.addWorkForm.type = "";
        }
      });
    },
    //加载任务  一个月一个库
    loadTodo(date) {
      let _this = this;
      if (
        _this.loadDate.year + "-" + _this.loadDate.moth !==
        date.year + "-" + date.moth
      ) {
        _this.aplaneTodoDb = new nedb({
          filename: "/data/aplane-todo_" + date.year + "-" + date.moth + ".db",
          autoload: true
        });
      }
      _this.loadDate = date;
      // 查询所有结果集
      _this.aplaneTodoDb.find(
        {
          year: _this.loadDate.year,
          moth: _this.loadDate.moth,
          date: _this.loadDate.date
        },
        function (err, docs) {
          _this.list = docs.sort(function (a, b) {
            let x = b.status === "进行中" ? 0 : 1;
            let y = a.status === "进行中" ? 0 : 1;
            return y - x;
          });
          _this.filterList();
        }
      );
    }
  },
  mounted() {
    let _this = this;
    document.addEventListener("click", this.clickOther);
    this.loadTypes();
    if (ipcRenderer) {
      //监听窗口变化
      ipcRenderer.on("main-plane-refresh-call", (event, data) => {
        let curTime = new Date();
        if (
          curTime.getFullYear() === _this.loadDate.year &&
          curTime.getMonth() === _this.loadDate.moth
        ) {
          _this.aplaneTodoDb = new nedb({
            filename:
              "/data/aplane-todo_" +
              _this.loadDate.year +
              "-" +
              _this.loadDate.moth +
              ".db",
            autoload: true
          });
          _this.loadTodo(_this.loadDate);
          globalBus.$emit("aPlane_reload", date => { });
        }
      });
    }


  },
  beforeDestroy() {
    // 实例销毁之前对点击事件进行解绑
    window.removeEventListener("click", this.clickOther);
    globalBus.$off("add_palne", this.add)
    globalBus.$off("edit_plane_by_form", this.editByForm)
    globalBus.$off("aDate_changeDateBack", this.changeDateBack);
    globalBus.$off("aPlane_reload", this.reloadPlane);
  }
};
</script>

<style lang="less">
.swal2-popup {
  background: #000000;
  box-shadow: 0px 0px 40px 0px #313131;
}

.swal2-input,
.swal2-title {
  color: #e6e6e6 !important
}
</style>
<style lang="less" scoped>
.theme-dark {
  .form-label {
    color: #fff;
  }

  .a-todo {
    background: #000000;

    .item.max {
      background: #232327;
    }

    .modal {
      background: rgba(50, 50, 50, 0.5);

      .modal-content {
        background: #000000;

        .m-title {
          color: #fff;
        }

        .form-control {
          background: transparent;
        }
      }
    }
  }

  .list {
    .d-title {
      color: #d3dae4;
    }

    .on-edit {
      color: #5d85a8 !important;
      background: #091122 !important;
    }

    .item:hover {
      color: #5d85a8;
      background: #18181b;
    }

    .opreation-max {
      background: #000000;
      box-shadow: 0 0 10px #000000;
    }

    .data-picker {
      background: #000000;
    }
  }
}

.theme-light {
  .a-todo {
    background: #ffffff;

    .item.max {
      background: #f9f9f9;
    }

    .modal {
      background: rgba(0, 0, 0, 0.4);

      .modal-content {
        background: #fff;

      }
    }

    .data-picker {
      background: #fff;
    }

  }

  .list {
    .d-title {
      color: #34495e;
    }

    .on-edit {
      color: #5d85a8 !important;
      background: #eceff1 !important;
    }

    .item:hover {
      color: #5d85a8;
      background: #eceff1;
    }

    .opreation-max {
      background: #eceff1;
      box-shadow: 0 0 10px #eceff1;
    }
  }

}

.a-todo {
  * {
    transition: all 0.2s linear;
  }

  .modal-content {
    width: 600px;
    margin: 0 auto;
    padding: 30px;
    box-sizing: border-box;
    border-radius: 10px;
    max-height: calc(100% - 100px);
    display: flex;
    flex-direction: column;
  }

  .list {
    .d-title {
      margin: 4px;
      font-weight: bold;
      font-size: 0.8rem;
    }
  }

  position: relative;
  transition: all 0.1s linear;
  overflow: hidden;
  display: flex;
  height: 100%;
  width: 100%;
  width: 312px;
  border-radius: 6px;
  box-sizing: border-box;
  padding: 0.625rem;

  .sweetalert2-add {
    cursor: pointer;
    white-space: nowrap;
    color: #78909c;
    transition: all 0.1s linear;
  }

  .sweetalert2-add:hover {
    color: #0288d1;
  }

  .add-pane-text {
    overflow: hidden;
    transition: all 0.2s linear;
    width: 0;
    padding: 10px 0;

    .textarea-bg {
      overflow: hidden;
      color: #969696;
      font-size: 0.9rem;
      position: absolute;
      left: 0;
      top: 0;
      height: calc(100% - 10px);
      width: 100%;
      padding: 10px 4px;
      box-sizing: border-box;
    }

    textarea {
      transition: none;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 99;
      height: calc(100% - 10px);
      width: 100%;
      margin: 0px;
      box-sizing: border-box;
      resize: vertical;
      background: transparent;
      padding: 10px 4px;
      font-family: auto;
      color: #546e7a;
      transition: all 0.3s linear;
      box-sizing: border-box;
      border: none;
      outline: none;
      border-bottom: 1px #cfd8dc solid;
    }

    textarea:focus+.textarea-bg {
      display: none;
    }
  }

  .add-pane {
    overflow: hidden;
    transition: all 0.2s linear;
    width: 0;
    padding: 10px 0;

    .select-type {
      display: flex;
      position: relative;

      .input-div {
        cursor: pointer;
        font-size: 0.9rem;
        padding: 10px 0;
        color: #546e7a;
        transition: all 0.3s linear;
        box-sizing: border-box;
        width: 100%;
        border-bottom: 1px #cfd8dc solid;
        display: flex;

        .text {
          padding: 0 4px;
          flex: 1;
        }

        span {
          line-height: 1.2rem;
        }
      }


      .fa-plus {
        cursor: pointer;
        line-height: 2.4rem;
        width: 3rem;
        text-align: center;
        color: #90a4ae;
      }

      .fa-plus:hover {
        color: #29b6f6;
      }
    }

    .add-bottom {
      width: 100%;
      text-align: right;
      display: flex;
    }

    .title {
      margin-bottom: 10px;
    }

    input,
    textarea,
    select {
      background: transparent;
      padding: 10px 4px;
      font-family: auto;
      color: #546e7a;
      transition: all 0.3s linear;
      box-sizing: border-box;
      margin: 0;
      width: 100%;
      border: none;
      outline: none;
      border-bottom: 1px #cfd8dc solid;
    }

    select {
      line-height: 2rem;
    }

    textarea {
      transition: none;
      margin-top: 20px;
      min-height: 3rem;
      // max-height: 8rem;
      resize: vertical;
    }

    input:focus,
    textarea:focus,
    select:focus {
      border-bottom: 1px #29b6f6 solid;
    }
  }

  .vpopmenu {
    position: fixed;
    background: #ffffff;
    padding: 10px;
    border-radius: 4px;
    box-shadow: 0px 0px 6px rgba(0, 0, 0, 0.2);
    transition: display 0.3s linear;

    .fa {
      width: 1.2rem;
    }

    div {
      transition: all 0.2s linear;
      margin: 4px 0;
      cursor: pointer;
      color: #69849b;
    }

    div:hover {
      color: #29b6f6;
    }

    .delete:hover {
      color: #f4511e;
    }
  }

  .title {
    line-height: 2rem;
    text-align: center;
    color: #69849b;

    .fa-plus,
    .fa-arrow-left,
    .fa-edit {
      position: absolute;
      left: 8px;
      top: 8px;
      cursor: pointer;
      transition: all 0.1s linear;
    }

    .fa-edit {
      left: 2rem;
    }

    .fa-check {
      color: #2e7d32;
      position: absolute;
      right: 8px;
      top: 8px;
      cursor: pointer;
      transition: all 0.1s linear;
    }

    .fa:hover {
      color: #29b6f6;
    }

    .fa-check:hover {
      color: #43a047;
    }
  }

  img {
    height: 0.8rem;
    width: 0.8rem;
    margin-right: 5px;
  }

  .list {
    transition: all 0.2s linear;
    width: 100%;
    overflow-y: auto;
    padding: 10px 0;

    .no-todo {
      color: #76838f;
      text-align: center;
      margin: 20px 0;

      span {
        color: #1565c0;
        cursor: pointer;
        transition: all 0.3s linear;
      }

      span:hover {
        color: #2196f3;
      }
    }

    .item.max {
      min-height: 4rem;
      margin-bottom: 8px;
      border-radius: 4px;
      position: relative;

      .item-title {
        white-space: normal;
        padding: 4px;
        color: #768692;
        font-weight: bold;
      }

      .item-detail {
        margin-bottom: 6px;
        color: #98aab8;
        font-size: 0.8rem;
      }

      .opreation-max {
        display: none;
        flex-direction: column;
        position: absolute;
        right: 0px;
        padding-right: 10px;
      }
    }

    .item {
      overflow: hidden;
      display: flex;
      color: #98aab8;
      cursor: pointer;
      padding: 0px 10px;
      transition: all 0.3s linear;

      .opreation {
        display: none;
      }

      .item-title {
        flex: 1;
        white-space: nowrap;
        /* 规定文本是否折行 */
        overflow: hidden;
        /* 规定超出内容宽度的元素隐藏 */
        text-overflow: ellipsis;
      }

      span {
        line-height: 2rem;
      }

      .fa-trash,
      .fa-repeat,
      .fa-check {
        text-align: right;
        width: 1.8rem;
      }

      .fa {
        transition: display 3s linear;
        transition: color 0.2s linear;
        transition: font-size 0.1s linear;
      }

      .fa:hover {
        font-size: 1.4rem;
        color: #00897b;
      }

      .fa-trash:hover {
        font-size: 1.4rem;
        color: #f4511e;
      }
    }

    .on-edit {
      border-radius: 4px !important;
    }

    .item:hover {
      border-radius: 4px;

      .opreation {
        display: block;
      }

      .opreation-max {
        display: flex;
      }
    }
  }
}

.modal.modal-show {
  z-index: 99;
  opacity: 1;
}

.modal {
  z-index: -1;
  opacity: 0;
  display: block;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
</style>